import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import useProTableConfig from '../../hooks/useProTableConfig';
import styles from './index.less';
// import type { FileRuleOTD } from '@/services/types/rulesCenter/modelManagement';
import { openEnum, parsingType, sensitiveEnum } from '@/enum';
import {
  CheckCircleFilled,
  ClockCircleFilled,
  CloseCircleFilled,
  CloudUploadOutlined,
  DownOutlined,
  ExclamationCircleOutlined,
  FileAddFilled,
  MinusCircleFilled,
} from '@ant-design/icons';
import { useModel } from '@umijs/max';
import { Button, Dropdown, message, Modal, Popconfirm, Space } from 'antd';
import hooks from '../../hooks';
const selectStatus = (status: string | undefined) => {
  switch (status) {
    case 'UNCLAIMED':
      return {
        color: 'processing',
      };
    case 'CLAIMED':
      return {
        color: 'success',
      };
  }
};
export default () => {
  const {
    tableRef,
    formRef,
    deleteRule,
    getTableList,
    selectedRowKeys,
    setSelectedRowKeys,
    setSelectedRows,
    setAnalysisVisible,
    setExportFileVisible,
    setCreateKnowledgeVisible,
    setCreateCorpusVisible,
    // setJsonViewVisible,

    // setViewVisible,
    // setType,
    // setUrl,
  } = hooks.useContainer();
  const { setJsonViewVisible, setViewVisible, setUrl, setType } = useModel('useTree', (model) => {
    return {
      setJsonViewVisible: model.setJsonViewVisible,
      setViewVisible: model.setViewVisible,
      setUrl: model.setUrl,
      setType: model.setType,
    };
  });

  const { confirm } = Modal;
  const proTableConfig = useProTableConfig({
    searchSpan: 8,

    optionRender(config, props, dom) {
      return [...dom.reverse()];
    },
    headerTitle: [
      <Dropdown
        key="menu"
        menu={{
          items: [
            {
              label: '批量解析',
              key: 'resolver',
            },
            {
              label: '批量删除',
              key: 'delete',
            },
          ],
          onClick: (e) => {
            if (selectedRowKeys.length === 0) {
              message.error('请选择文件');
              return;
            }
            if (e.key === 'resolver') {
              setAnalysisVisible(true);
            } else if (e.key === 'delete') {
              confirm({
                title: '确认删除选中任务?',
                icon: <ExclamationCircleOutlined />,
                content: `当前选中${selectedRowKeys.length}条数据`,
                okText: '确认',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                  deleteRule.run(selectedRowKeys);
                },
              });
            }
          },
        }}
      >
        <Button type="primary">
          批量操作
          <DownOutlined />
        </Button>
      </Dropdown>,
    ],
    searchText: '搜索',
  });

  const tableColumns: ProColumns<any>[] = [
    {
      title: '序号',
      width: 60,
      hideInSearch: true,
      fixed: 'left',
      renderText: (_: any, __: any, index: number) => index + 1,
    },

    {
      title: '原始数据名称',
      dataIndex: 'fileName',
      ellipsis: true,
      width: 180,
      order: 4,
    },
    // {
    //   title: '文件摘要',
    //   dataIndex: 'content',
    //   width: 160,
    //   ellipsis: true,
    //   hideInSearch: true,
    //   renderText: (_, record) => {
    //     return <span title={record.content}>{record.content}</span>;
    //   },
    // },
    {
      title: '公开属性',
      dataIndex: 'openProperty',

      width: 126,
      hideInSearch: true,
      renderText: (_, record) => {
        return <>{openEnum[record.openProperty + '']}</>;
      },
    },
    {
      title: '敏感等级',
      width: 126,
      dataIndex: 'sensitiveLevel',
      hideInSearch: true,
      renderText: (_, record) => {
        return <>{sensitiveEnum[record.sensitiveLevel + '']}</>;
      },
    },

    {
      title: '原始数据类型',
      dataIndex: 'suffix',
      ellipsis: false,
      width: 120,
    },
    {
      title: '上传时间',
      width: 126,
      dataIndex: 'createTime',
      hideInSearch: false,
    },
    {
      title: '上传时间',
      dataIndex: 'createTime',
      ellipsis: false,
      hideInTable: true,
      width: 160,
      valueType: 'dateRange',
      // renderText: (value) => (value ? moment(value).format('YYYY/MM/DD HH:mm:ss') : '-'),
      search: {
        transform: (value) => {
          return {
            createTime: value[0],
            endTime: value[1],
          };
        },
      },
    },

    {
      title: '解析状态',
      dataIndex: 'status',
      ellipsis: false,
      width: 160,
      order: 1,
      valueType: 'select',
      fieldProps: {
        options: parsingType,
      },
      renderText: (_, record) => {
        return (
          <>
            <span key={1}>
              {record?.status === 3 ? (
                <ClockCircleFilled style={{ color: 'green' }} />
              ) : record?.status === 0 ? (
                <CheckCircleFilled style={{ color: 'orange' }} />
              ) : record?.status === 1 ? (
                <MinusCircleFilled style={{ color: '#1890ff' }} />
              ) : record?.status === 2 ? (
                <CloseCircleFilled style={{ color: 'red' }} />
              ) : (
                <CloseCircleFilled style={{ color: 'yellow' }} />
              )}
              <span style={{ marginLeft: '5.0px' }}>
                {record.status === 0
                  ? '暂缓解析'
                  : record.status === 1
                  ? '解析中'
                  : record.status === 2
                  ? '解析失败'
                  : record.status === 3
                  ? '解析成功'
                  : '待解析'}
              </span>
            </span>
          </>
        );
      },
    },
    {
      title: '所属知识库',
      dataIndex: 'knowledges',
      ellipsis: true,
      width: 120,
    },

    {
      title: '操作',
      width: 160,
      dataIndex: 'operate',
      hideInSearch: true,
      fixed: 'right',
      renderText: (text, record) => {
        return (
          <Space size="small" className={styles.spaceWrap}>
            <a
              onClick={() => {
                setUrl(record.fileId);
                setType(record.suffix === 'doc' ? 'docx' : record.suffix);
                if (record.suffix.indexOf('json') > -1 || record.suffix === 'txt') {
                  setJsonViewVisible(true);
                } else if (
                  record.suffix === 'docx' ||
                  record.suffix === 'pdf' ||
                  record.suffix === 'doc'
                ) {
                  setViewVisible(true);
                } else {
                  message.success('暂不支持预览');
                }
              }}
            >
              原始数据预览
            </a>
            <a
              onClick={() => {
                window.open(
                  `${window.location.origin}/corpus/resource/downloadFile?id=${record?.id}`,
                );
              }}
            >
              原始数据下载
            </a>
            <Popconfirm
              key="delete"
              title="确认是否删除？"
              onConfirm={() => {
                deleteRule.run([record.id]);
              }}
            >
              <a style={{ color: '#f02323' }}>删除</a>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  return (
    <ProTable
      {...proTableConfig}
      actionRef={tableRef}
      formRef={formRef}
      columns={tableColumns}
      form={{
        ignoreRules: false,
      }}
      request={getTableList.runAsync}
      size="middle"
      rowKey="id"
      scroll={{ x: 'calc(1080px + 50%)' }}
      rowSelection={{
        defaultSelectedRowKeys: [],
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
          console.log(selectedRowKeys);

          setSelectedRowKeys(selectedRowKeys);
          setSelectedRows(selectedRows);
        },
      }}
      toolBarRender={() => [
        <Button
          key="create"
          icon={<FileAddFilled />}
          onClick={() => {
            setCreateKnowledgeVisible(true);
          }}
          style={{ marginRight: 10 }}
          type="primary"
        >
          生成知识库
        </Button>,
        <Button
          key="create"
          icon={<FileAddFilled />}
          onClick={() => {
            if (selectedRowKeys.length === 0) {
              message.error('请选择文件');
              return;
            }
            setCreateCorpusVisible(true);
          }}
          style={{ marginRight: 10 }}
          type="primary"
        >
          生成语料库
        </Button>,
        <Button
          key="import"
          icon={<CloudUploadOutlined />}
          type="primary"
          onClick={() => {
            setExportFileVisible(true);
          }}
        >
          批量导入
        </Button>,
        <Button
          key="goback"
          onClick={() => {
            history.go(-1);
          }}
        >
          返回
        </Button>,
      ]}
    />
  );
};
